package com.itheima.web.aspect;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.domain.system.SysLog;
import com.itheima.service.system.SysLogService;
import com.itheima.web.controller.BaseController;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

@Aspect
@Component
public class WriteLog extends BaseController {

    @Reference
    private SysLogService sysLogService;

    //切点
    @Pointcut("execution(* com.itheima.web.controller.*.*.*(..))")
    public void pt() {
    }

    //环绕通知
    @Around("pt()")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        //记录日志
        SysLog sysLog = new SysLog();

        //自己生成
        sysLog.setId(UUID.randomUUID().toString());
        sysLog.setTime(new Date());

        //request
        sysLog.setIp(request.getRemoteAddr());

        //session
        sysLog.setUserName(getLoginUser().getUserName());
        sysLog.setCompanyId(getCompanyId());
        sysLog.setCompanyName(getCompanyName());

        //暂时搞不定
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Method method = methodSignature.getMethod();

        sysLog.setMethod(method.getName());//方法名

        if (method.isAnnotationPresent(RequestMapping.class)) {
            RequestMapping annotation = method.getAnnotation(RequestMapping.class);
            String name = annotation.name();
            sysLog.setAction(name);//方法上的注解的name属性的值
        }

        //保存日志到数据库
        sysLogService.save(sysLog);

        //切点方法执行
        return pjp.proceed();
    }
}
